﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Security.Policy;
using System.Text; 
using System.IO;
using DTCash.Logger;
using DTCash.Logger.DTO;

namespace Uranus.Common
{
    public class FileCommon
    {
        public static bool DeleteFile(string filepath)
        {
            bool state = false;
            if (File.Exists(filepath))
            {
                try
                {
                    File.Delete(filepath);
                    state = true;
                }
                catch
                {
                    LogHelper.WriteLog(LogEnum.Error, "删除文件失败", "请求删除文件 " + filepath + " 失败");
                }
            }
            return state;
        }

        /// 将 Stream 转成 byte[]

        public static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// 将 byte[] 转成 Stream

        public static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }

        /// <summary>
        /// 下载远程文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static MemoryStream DownFile(string url)
        {
            try
            {
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
                //hwr.AddRange(0, 10000000);
                Stream stream = hwr.GetResponse().GetResponseStream();
                MemoryStream ms = new MemoryStream();
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int sz = stream.Read(buffer, 0, 1024);
                    if (sz == 0) break;
                    ms.Write(buffer, 0, sz);
                }
                stream.Close();
                ms.Position = 0;
                return ms;
            }
            catch (Exception ex)
            {
                
                throw new Exception(string.Format("url:{0} message:{1}",url,ex.Message),ex);
            }

        }

        /// <summary>
        /// 下载图片到本地目录
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="fileSavePath"></param>
        /// <returns></returns>
        public static bool DownLoadWebFile(string fileUrl, string fileSavePath)
        {
            HttpWebRequest myReq = null;
            HttpWebResponse webResponse = null;
            try
            {
                myReq = (HttpWebRequest)HttpWebRequest.Create(fileUrl);
                myReq.AllowAutoRedirect = true;
                webResponse = (HttpWebResponse)myReq.GetResponse();
            }
            catch
            {
                return false;
            }

            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int readBytes = 0;
            try
            {
                using (FileStream stream = new FileStream(fileSavePath, FileMode.Append))
                {
                    Stream sr = null;
                    try
                    {
                        sr = webResponse.GetResponseStream();
                        do
                        {
                            readBytes = sr.Read(buffer, 0, bufferSize);
                            stream.Write(buffer, 0, readBytes);
                        }
                        while (readBytes != 0);
                    }
                    catch
                    {
                        return false;
                    }
                    finally
                    {
                        try
                        {
                            sr.Close();
                            stream.Close();
                        }
                        catch
                        {
                        }
                    }
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// description：http post请求客户端
        /// last-modified-date：2012-02-28
        /// </summary>
        public class HttpRequestClient
        {
            #region //字段
            private ArrayList bytesArray;
            private Encoding encoding = Encoding.UTF8;
            private string boundary = String.Empty;
            #endregion

            #region //构造方法
            public HttpRequestClient()
            {
                bytesArray = new ArrayList();
                string flag = DateTime.Now.Ticks.ToString("x");
                boundary = "---------------------------" + flag;
            }
            #endregion

            #region //方法
            /// <summary>
            /// 合并请求数据
            /// </summary>
            /// <returns></returns>
            private byte[] MergeContent()
            {
                int length = 0;
                int readLength = 0;
                string endBoundary = "--" + boundary + "--\r\n";
                byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);

                bytesArray.Add(endBoundaryBytes);

                foreach (byte[] b in bytesArray)
                {
                    length += b.Length;
                }

                byte[] bytes = new byte[length];

                foreach (byte[] b in bytesArray)
                {
                    b.CopyTo(bytes, readLength);
                    readLength += b.Length;
                }

                return bytes;
            }

            /// <summary>
            /// 上传
            /// </summary>
            /// <param name="requestUrl">请求url</param>
            /// <param name="responseText">响应</param>
            /// <returns></returns>
            public bool Upload(String requestUrl, out String responseText)
            {
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);

                byte[] responseBytes;
                byte[] bytes = MergeContent();

                try
                {
                    responseBytes = webClient.UploadData(requestUrl, bytes);
                    responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                    return true;
                }
                catch (WebException ex)
                {
                    Stream responseStream = ex.Response.GetResponseStream();
                    responseBytes = new byte[ex.Response.ContentLength];
                    responseStream.Read(responseBytes, 0, responseBytes.Length);
                }
                responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                return false;
            }

            /// <summary>
            /// 设置表单数据字段
            /// </summary>
            /// <param name="fieldName">字段名</param>
            /// <param name="fieldValue">字段值</param>
            /// <returns></returns>
            public void SetFieldValue(String fieldName, String fieldValue)
            {
                string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                string httpRowData = String.Format(httpRow, fieldName, fieldValue);

                bytesArray.Add(encoding.GetBytes(httpRowData));
            }

            /// <summary>
            /// 设置表单文件数据
            /// </summary>
            /// <param name="fieldName">字段名</param>
            /// <param name="filename">字段值</param>
            /// <param name="contentType">内容内型</param>
            /// <param name="fileBytes">文件字节流</param>
            /// <returns></returns>
            public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
            {
                string end = "\r\n";
                string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string httpRowData = String.Format(httpRow, fieldName, filename, contentType);

                byte[] headerBytes = encoding.GetBytes(httpRowData);
                byte[] endBytes = encoding.GetBytes(end);
                byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length];

                headerBytes.CopyTo(fileDataBytes, 0);
                fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
                endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length);

                bytesArray.Add(fileDataBytes);
            }
            #endregion
        }

    }
}